/*
 * @Author: sun
 * @Date: 2022-04-12 17:52:21
 * @LastEditTime: 2022-04-12 17:59:42
 * @LastEditors: sun
 * @Description:
 */
import axios from "axios";
import { Notify, Dialog } from "vant";
import store from "@/store";
import { getToken } from "@/utils/auth";

// create an axios instance
const service = axios.create({
	baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
	// withCredentials: true, // send cookies when cross-domain requests
	timeout: 5000 // request timeout
});

// request interceptor
service.interceptors.request.use(
	config => {
		if (store.getters.token) {
			config.headers["X-Token"] = getToken();
		}
		return config;
	},
	error => {
		console.log(error); // for debug
		return Promise.reject(error);
	}
);

// response interceptor
service.interceptors.response.use(
	response => {
		const res = response.data;

		if (res.code !== 200) {
			Notify({
				message: res.message || "Error",
				type: "warning",
				duration: 5 * 1000
			});
			// logged out
			if ([50008, 50009, 50010].includes(res.code)) {
				Dialog.alert({
					message: "生命远不止连轴转和忙到极限，人类的体验远比这辽阔、丰富得多。",
					theme: "round-button"
				}).then(() => {
					// on close
				});
			}
			return Promise.reject(new Error(res.message || "Error"));
		} else {
			return res;
		}
	},
	error => {
		console.log("err" + error); // for debug
		Notify({
			message: error.message,
			type: "warning",
			duration: 5 * 1000
		});
		return Promise.reject(error);
	}
);

export default service;
